package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Proclamation;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.LikesVo;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private ProclamationApi proclamationApi;
    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private CommentApi commentApi;

    /**
     * 根据环信id查询用户详情
     */
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1、根据环信id查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2、根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加好友关系
    public void contacts(Long friendId) {
        //1、将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        if(!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
        //2、如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(),friendId);
    }

    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        List<Long> idlist = new ArrayList<>();
        if (keyword!=null){
            List<UserInfo> byname = userInfoApi.findByname(keyword);
            idlist = CollUtil.getFieldValues(byname,"id",Long.class);
        }
        //1、调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.findByUserId(UserHolder.getUserId(),page,pagesize,idlist);
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //2、提取数据列表中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //3、调用UserInfoAPI查询好友的用户详情
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //4、构造VO对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if(userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //分页查询公告
    public PageResult selectPage(Integer page, Integer pagesize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        List<Proclamation> proclamations = proclamationApi.selectPage(page, pagesize);
        if (proclamations.size()==0){
            pageResult.setCounts(0L);
            pageResult.setItems(null);
            return pageResult;
        }
        Long count = proclamationApi.getcount();
        pageResult.setCounts(count);
        List<ProclamationVo> list = new ArrayList<>();
        for (Proclamation proclamation : proclamations) {
            ProclamationVo init = ProclamationVo.init(proclamation);
            list.add(init);
        }
        pageResult.setItems(list);
        return pageResult;
    }


    /**
     * 消息喜欢列表
     */
    public PageResult findLoves(Integer page, Integer pagesize) {
        //1.得到userId
        Long userId = UserHolder.get().getId();
        //2.根据userId分页查询喜欢列表
        PageResult pageResult = userLikeApi.findPageByUserId(page,pagesize,userId);
        List<UserLike> userLikes = (List<UserLike>) pageResult.getItems();
        //3.提取出喜欢的用户id
        List<Long> likeUserIds = CollUtil.getFieldValues(userLikes, "likeUserId", Long.class);
        //4.根据喜欢的用户id查询userInfo
        Map<Long, UserInfo> userInfoMap = userInfoApi.findMapByids(likeUserIds);
        //5.将用户封装到UserLikeVo
        List<LikesVo> vos = new ArrayList<>();
        for (UserLike userLike : userLikes) {
            UserInfo userInfo = userInfoMap.get(userLike.getLikeUserId());
            LikesVo vo = LikesVo.init(userInfo, userLike);
            vos.add(vo);
        }
        pageResult.setItems(vos);
        return pageResult;

    }
    /**
     * 消息点赞列表
     */
    public PageResult findLikes(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();

        List<Comment> list = commentApi.findLikesByUserId(page, pagesize, userId, CommentType.LIKE );
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        List<Long> publishUserId = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(publishUserId, new UserInfo());
        ArrayList<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }

    public PageResult findComments(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        List<Comment> list = commentApi.findLikesByUserId (page, pagesize, userId, CommentType.COMMENT);

        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        List<Long> publishUserId = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(publishUserId, new UserInfo());
        ArrayList<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0l, vos);
    }

}
